<template>
  <div v-if="flower" class="flower-detail-container">
    <!-- 顶部导航 -->
    <div class="detail-header">
      <button class="back-button" @click="navigateBack">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <polyline points="15 18 9 12 15 6"></polyline>
        </svg>
        返回列表
      </button>
    </div>
    
    <!-- 花卉基本信息 -->
    <div class="flower-basic-info">
      <div class="flower-main-image">
        <img :src="flower.image" :alt="flower.name" class="main-image" />
      </div>
      
      <div class="flower-details">
        <div class="flower-header">
          <h1 class="flower-name">{{ flower.name }}</h1>
          <p class="flower-scientific-name">{{ flower.scientificName }}</p>
        </div>
        
        <!-- 花卉价格和库存 -->
        <div class="flower-price-section">
          <div class="flower-price">¥{{ flower.price.toFixed(2) }}</div>
          <div class="flower-unit">/ {{ flower.unit }}</div>
          <div class="flower-stock">库存: {{ flower.stock }} {{ flower.unit }}</div>
        </div>

        <div class="flower-meta">
          <div class="meta-item">
            <span class="meta-label">分类</span>
            <span class="meta-value">{{ flower.category }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">原产地</span>
            <span class="meta-value">{{ flower.origin }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">花期</span>
            <span class="meta-value">{{ flower.floweringSeason }}</span>
          </div>
        </div>
        
        <div class="flower-description">
          <h3>花卉简介</h3>
          <p>{{ flower.description }}</p>
        </div>
        
        <div class="flower-care-tips">
          <h3>养护小贴士</h3>
          <p>{{ flower.careTips }}</p>
        </div>

        <!-- 购买功能 -->
        <div class="purchase-section">
          <div class="quantity-selector">
            <button 
              class="quantity-btn minus" 
              @click="decreaseQuantity" 
              :disabled="quantity <= 1"
            >
              -
            </button>
            <input 
              type="number" 
              v-model.number="quantity" 
              class="quantity-input" 
              min="1" 
              :max="flower.stock"
            />
            <button 
              class="quantity-btn plus" 
              @click="increaseQuantity" 
              :disabled="quantity >= flower.stock"
            >
              +
            </button>
          </div>
          
          <button 
            class="add-to-cart-btn" 
            @click="handleAddToCart"
            :disabled="flower.stock <= 0"
          >
            {{ flower.stock <= 0 ? '库存不足' : '加入购物车' }}
          </button>
        </div>
      </div>
    </div>
    
    <!-- 评论区 -->
    <div class="comments-section">
      <div class="comments-header">
        <h2>评论 ({{ flower.comments.length }})</h2>
      </div>
      
      <!-- 评论表单 -->
      <div class="comment-form-wrapper" v-if="isLoggedIn">
        <form class="comment-form" @submit.prevent="submitComment">
          <textarea
            v-model="commentText"
            placeholder="分享你对这种花卉的看法..."
            class="comment-input"
            rows="3"
            required
          ></textarea>
          <div class="comment-actions">
            <button type="submit" class="submit-button" :disabled="!commentText.trim()">
              发表评论
            </button>
          </div>
        </form>
      </div>
      
      <!-- 未登录提示 -->
      <div v-else class="login-prompt">
        <p>请先<a href="/login" class="login-link">登录</a>后发表评论</p>
      </div>
      
      <!-- 评论列表 -->
      <div class="comments-list">
        <div v-if="flower.comments.length === 0" class="no-comments">
          <p>暂无评论，快来发表第一条评论吧！</p>
        </div>
        
        <div v-for="comment in flower.comments" :key="comment.id" class="comment-item">
          <div class="comment-avatar">
            {{ getAvatarInitial(comment.userName) }}
          </div>
          <div class="comment-content">
            <div class="comment-header-info">
              <span class="comment-author">{{ comment.userName }}</span>
              <span class="comment-time">{{ formatDate(comment.createdAt) }}</span>
            </div>
            <p class="comment-text">{{ comment.content }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 加载状态 -->
  <div v-else-if="isLoading" class="loading-state">
    <div class="loading-spinner"></div>
    <p>加载中...</p>
  </div>
  
  <!-- 错误状态 -->
  <div v-else class="error-state">
    <h3>花卉不存在</h3>
    <p>抱歉，您访问的花卉信息不存在或已被删除。</p>
    <button class="back-to-list" @click="navigateToHome">返回列表</button>
  </div>
</template>

<script setup>
/**
 * 花卉详情视图：
 * - 根据路由参数 :id 展示具体花卉信息
 * - 支持加入购物车等操作（若有）
 */
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getFlowerById, addComment, isUserLoggedIn, getCurrentUser, addToCart } from '../services/dataService';

const route = useRoute();
const router = useRouter();
const flower = ref(null);
const isLoading = ref(true);
const commentText = ref('');
const isLoggedIn = ref(false);
const currentUser = ref(null);
const quantity = ref(1);

// 加载花卉详情
onMounted(() => {
  const flowerId = route.params.id;
  loadFlowerDetail(flowerId);
  
  // 检查用户登录状态
  checkLoginStatus();
  
  // 监听localStorage变化
  window.addEventListener('storage', checkLoginStatus);
});

// 检查登录状态的函数
const checkLoginStatus = () => {
  isLoggedIn.value = isUserLoggedIn();
  currentUser.value = getCurrentUser();
};

// 监听路由参数变化，重新加载数据
watch(() => route.params.id, (newId) => {
  if (newId) {
    loadFlowerDetail(newId);
    checkLoginStatus(); // 重新检查登录状态
  }
});

const loadFlowerDetail = (id) => {
  isLoading.value = true;
  
  try {
    // 模拟异步加载
    setTimeout(() => {
      const flowerDetail = getFlowerById(id);
      flower.value = flowerDetail;
      isLoading.value = false;
    }, 500);
  } catch (error) {
    console.error('Failed to load flower detail:', error);
    isLoading.value = false;
  }
};

// 提交评论
const submitComment = () => {
  if (!commentText.value.trim() || !currentUser.value) return;
  
  const result = addComment(flower.value.id, {
    userId: currentUser.value.id,
    userName: currentUser.value.username,
    content: commentText.value.trim()
  });
  
  if (result.success) {
    // 重新加载花卉详情以更新评论列表
    loadFlowerDetail(flower.value.id);
    commentText.value = '';
  } else {
    alert('评论提交失败，请稍后重试');
  }
};

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const now = new Date();
  const diffInSeconds = Math.floor((now - date) / 1000);
  
  if (diffInSeconds < 60) {
    return `${diffInSeconds}秒前`;
  } else if (diffInSeconds < 3600) {
    return `${Math.floor(diffInSeconds / 60)}分钟前`;
  } else if (diffInSeconds < 86400) {
    return `${Math.floor(diffInSeconds / 3600)}小时前`;
  } else if (diffInSeconds < 604800) {
    return `${Math.floor(diffInSeconds / 86400)}天前`;
  } else {
    return date.toLocaleDateString('zh-CN');
  }
};

// 减少购买数量
const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--;
  }
};

// 增加购买数量
const increaseQuantity = () => {
  if (flower.value && quantity.value < flower.value.stock) {
    quantity.value++;
  }
};

// 处理加入购物车
const handleAddToCart = () => {
  if (!flower.value || flower.value.stock <= 0) return;
  
  const result = addToCart(flower.value.id, quantity.value);
  
  if (result.success) {
    alert('已成功加入购物车！');
    // 可以添加购物车图标更新逻辑
    // 触发自定义事件通知父组件更新购物车数量
    window.dispatchEvent(new Event('cartUpdated'));
  } else {
    alert('加入购物车失败：' + result.message);
  }
};

// 获取用户名首字母用于头像
const getAvatarInitial = (username) => {
  return username.charAt(0).toUpperCase();
};

// 导航返回
const navigateBack = () => {
  router.go(-1);
};

// 导航到首页
const navigateToHome = () => {
  router.push('/');
};
</script>

<style scoped>
.flower-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.detail-header {
  margin-bottom: 20px;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background: white;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #555;
  cursor: pointer;
  transition: all 0.3s ease;
}

.back-button:hover {
  border-color: #667eea;
  color: #667eea;
}

.flower-basic-info {
  display: grid;
  grid-template-columns: 1fr 1.5fr;
  gap: 40px;
  margin-bottom: 60px;
  background: white;
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
}

.flower-main-image {
  position: relative;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.main-image {
  width: 100%;
  height: auto;
  display: block;
  transition: transform 0.5s ease;
}

.flower-main-image:hover .main-image {
  transform: scale(1.05);
}

.flower-details {
  display: flex;
  flex-direction: column;
}

.flower-header {
  margin-bottom: 30px;
}

.flower-name {
  font-size: 36px;
  font-weight: 700;
  color: #333;
  margin: 0 0 10px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.flower-scientific-name {
  font-size: 18px;
  font-style: italic;
  color: #888;
  margin: 0;
}

.flower-meta {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.meta-item {
  background: #f8fafc;
  padding: 15px;
  border-radius: 12px;
  border-left: 4px solid #667eea;
}

.meta-label {
  display: block;
  font-size: 12px;
  font-weight: 600;
  color: #94a3b8;
  margin-bottom: 5px;
  text-transform: uppercase;
}

.meta-value {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.flower-description,
.flower-care-tips {
  margin-bottom: 25px;
}

.flower-description h3,
.flower-care-tips h3 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.flower-description p,
.flower-care-tips p {
  font-size: 16px;
  line-height: 1.6;
  color: #666;
  margin: 0;
}

/* 价格和库存样式 */
.flower-price-section {
  margin: 1.5rem 0;
  display: flex;
  align-items: baseline;
  gap: 0.5rem;
}

.flower-price {
  font-size: 2rem;
  font-weight: bold;
  color: #ff6b6b;
}

.flower-unit {
  color: #666;
}

.flower-stock {
  margin-left: auto;
  color: #8E8C41;
  font-size: 0.9rem;
}

/* 购买功能样式 */
.purchase-section {
  margin: 2rem 0;
  display: flex;
  align-items: center;
  gap: 1.5rem;
}

.quantity-selector {
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 8px;
  overflow: hidden;
}

.quantity-btn {
  width: 36px;
  height: 36px;
  background: transparent;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  transition: background-color 0.3s;
}

.quantity-btn:hover:not(:disabled) {
  background: #e0e0e0;
}

.quantity-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quantity-input {
  width: 50px;
  height: 36px;
  text-align: center;
  border: none;
  background: transparent;
  outline: none;
  font-size: 1rem;
}

.add-to-cart-btn {
  padding: 0.8rem 2rem;
  background: #8E8C41;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.add-to-cart-btn:hover:not(:disabled) {
  background: #6c6a2d;
}

.add-to-cart-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.comments-section {
  background: white;
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
}

.comments-header {
  margin-bottom: 30px;
}

.comments-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.comment-form-wrapper {
  margin-bottom: 40px;
}

.comment-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.comment-input {
  padding: 15px;
  border: 2px solid #e1e5e9;
  border-radius: 12px;
  font-size: 16px;
  font-family: inherit;
  resize: vertical;
  transition: border-color 0.3s ease;
}

.comment-input:focus {
  outline: none;
  border-color: #667eea;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
}

.submit-button {
  padding: 12px 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.3);
}

.submit-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.login-prompt {
  text-align: center;
  padding: 30px;
  background: #f8fafc;
  border-radius: 12px;
  margin-bottom: 40px;
}

.login-prompt p {
  color: #666;
  margin: 0;
}

.login-link {
  color: #667eea;
  font-weight: 500;
  text-decoration: none;
}

.login-link:hover {
  text-decoration: underline;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.no-comments {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.comment-item {
  display: flex;
  gap: 15px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 12px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.comment-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 16px;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
}

.comment-header-info {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.comment-time {
  font-size: 12px;
  color: #94a3b8;
}

.comment-text {
  font-size: 14px;
  line-height: 1.5;
  color: #666;
  margin: 0;
  word-wrap: break-word;
}

.loading-state,
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e1e5e9;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-state h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.error-state p {
  color: #666;
  margin-bottom: 20px;
}

.back-to-list {
  padding: 10px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.back-to-list:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

@media (max-width: 992px) {
  .flower-basic-info {
    grid-template-columns: 1fr;
    gap: 30px;
    padding: 30px;
  }
  
  .flower-name {
    font-size: 28px;
  }
  
  .flower-meta {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .flower-detail-container {
    padding: 15px;
  }
  
  .flower-basic-info,
  .comments-section {
    padding: 20px;
  }
  
  .flower-name {
    font-size: 24px;
  }
  
  .flower-description p,
  .flower-care-tips p {
    font-size: 15px;
  }
}
</style>